<?php

class SJB_Admin_Classifieds_ImportListings extends SJB_Function
{
	public function isAccessible()
	{
		$this->setPermissionLabel('import_listings');
		return parent::isAccessible();
	}

	public function execute()
	{
		if (PHP_VERSION_IS_LOWER_THAN) {
			echo PHP_VERSION_IS_LOWER_MESSAGE;
			return null;
		}

		$template_processor = SJB_System::getTemplateProcessor();
		$file_info = isset($_FILES['import_file']) ? $_FILES['import_file'] : null;
		$listing_type_id = SJB_Request::getVar('listing_type_id', null);
		$productSID = SJB_Request::getVar('product_sid', 0);
		$errors = array();

		if ($listing_type_id && $productSID) {
			$acl = SJB_Acl::getInstance();
			$resource = 'post_' . strtolower($listing_type_id);
			if (!$acl->isAllowed($resource, $productSID, 'product'))
				$errors[] = 'You cannot import listings of this type under the selected product';
		}

		if (empty($file_info) || $file_info['error'] == UPLOAD_ERR_NO_FILE || $errors) {

			if ($file_info['error'] == UPLOAD_ERR_NO_FILE)
				$errors[] = 'Please choose exl or csv file';
			$listing_types = SJB_ListingTypeManager::getAllListingTypesInfo();
			$products = SJB_ProductsManager::getProductsByProductType('post_listings');
			$template_processor->assign('listing_types', $listing_types);
			$template_processor->assign('products', $products);
			$template_processor->assign('errors', $errors);
			$template_processor->display('import_listings.tpl');
		}
		else {
			$i18n = SJB_I18N::getInstance();
			$csv_delimiter = SJB_Request::getVar('csv_delimiter', null);
			$active_status = SJB_Request::getVar('active', 0);
			$activation_date = SJB_Request::getVar('activation_date', date('Y-m-d'));
			$activation_date = $i18n->getInput('date', $activation_date);
			$non_existed_values_flag = SJB_Request::getVar('non_existed_values', null);
			$productInfo = SJB_ProductsManager::getProductInfoBySID($productSID);
			$timestamp = strtotime($activation_date . ' + ' . $productInfo['listing_duration'] . ' days');
			$expiration_date = $i18n->getDate(date('Y-m-d', $timestamp));

			$extension = $_REQUEST['file_type'];

			if ($extension == 'xls') $import_file = new SJB_ImportFileXLS($file_info);
			elseif ($extension == 'csv') $import_file = new SJB_ImportFileCSV($file_info, $csv_delimiter);

			$import_file->parse();

			$listing = $this->CreateListing(array(), $listing_type_id);

			$imported_data_processor = new SJB_ImportedDataProcessor($import_file->getData(), $listing);
			$import_file_url = false;
			$count = 0;
			while (!$imported_data_processor->isEmpty()) {
				$count++;
				$listing_info = $imported_data_processor->getData($non_existed_values_flag);
				$doc = new DOMDocument();
				foreach ($listing->getProperties() as $property) {
					if ($property->getType() == 'complex' && !empty($listing_info[$property->id])) {
						$childFields = SJB_ListingComplexFieldManager::getListingFieldsInfoByParentSID($property->sid);
						$doc->loadXML($listing_info[$property->id]);
						$results = $doc->getElementsByTagName($property->id . 's');
						$listing_info[$property->id] = array();
						foreach ($results as $complexparent) {
							$i = 1;
							foreach ($complexparent->getElementsByTagName($property->id) as $result) {
								$resultXML = simplexml_import_dom($result);
								foreach ($childFields as $childField) {
									if (isset($resultXML->$childField['id']))
										$listing_info[$property->id][$childField['id']][$i] = (string)$resultXML->$childField['id'];
								}
								$i++;
							}
						}
					}
					elseif ($property->getType() == 'monetary' && !empty($listing_info[$property->id])) {
						$value = $listing_info[$property->id];
						$listing_info[$property->id] = array();
						$listing_info[$property->id]['value'] = $value;
						$defaultCurrency = SJB_CurrencyManager::getDefaultCurrency();
						$currencyCode = !empty($listing_info[$property->id . "Currency"]) ? $listing_info[$property->id . "Currency"] : $defaultCurrency['currency_code'];
						$currency = SJB_CurrencyManager::getCurrencyByCurrCode($currencyCode);
						$listing_info[$property->id]['add_parameter'] = !empty($currency['sid']) ? $currency['sid'] : '';
						if (isset($listing_info[$property->id . "Currency"]))
							unset($listing_info[$property->id . "Currency"]);
					}
				}

				$listing = $this->CreateListing($listing_info, $listing_type_id);

				$listing->addActiveProperty($active_status);
				$listing->addActivationDateProperty($activation_date);
				$listing->addExpirationDateProperty($expiration_date);
				$listing->setProductInfo(SJB_ProductsManager::getProductExtraInfoBySID($productSID));
				$listing->setPropertyValue('access_type', 'everyone');
				$listing->setPropertyValue('status', 'approved');

				foreach ($listing->getProperties() as $property) {
					if ($property->getType() == 'tree' && $property->value !== '') {
						$treeValues = explode(",", $property->value);
						$treeSIDs = array();
						foreach ($treeValues as $treeValue) {
							$info = SJB_ListingFieldTreeManager::getItemInfoByCaption($property->sid, trim($treeValue));
							$treeSIDs[] = $info['sid'];
						}
						$listing->setPropertyValue($property->id, implode(',', $treeSIDs));
						$listing->details->properties[$property->id]->type->property_info['value'] = implode(',', $treeSIDs);
					}

					// fix for new format of ApplicationSettings
					elseif ($property->id == 'ApplicationSettings' && !empty($listing_info['ApplicationSettings'])) {
						if (preg_match("^[a-z0-9\._-]+@[a-z0-9\._-]+\.[a-z]{2,4}\$^iu", $listing_info['ApplicationSettings']))
							$listing_info['ApplicationSettings'] = array('value' => $listing_info['ApplicationSettings'], 'add_parameter' => 1);
						elseif (preg_match("^(https?:\/\/)^", $listing_info['ApplicationSettings']))
							$listing_info['ApplicationSettings'] = array('value' => $listing_info['ApplicationSettings'], 'add_parameter' => 2);
						else
							$listing_info['ApplicationSettings'] = array('value' => '', 'add_parameter' => ''); //put empty if not valid email or url
						$listing->details->properties[$property->id]->type->property_info['value'] = $listing_info['ApplicationSettings'];
					}
					elseif ($property->getType() == 'complex') {
						$childFields = SJB_ListingComplexFieldManager::getListingFieldsInfoByParentSID($property->sid);
						$complexChildValues = $property->value;
						foreach ($childFields as $childField) {
							if (($childField['type'] == 'complexfile' || $childField['type'] == 'complexvideo') && !empty($complexChildValues[$childField['id']])) {
								$field_info = SJB_ListingComplexFieldManager::getFieldInfoBySID($childField['sid']);
								if (SJB_UploadFileManager::fileImport($listing_info, $field_info, $property->id)) {
									$import_file_url = true;
								}
							}
							if ($property->type->complex->details->properties[$childField['id']]->value == null) {
								$property->type->complex->details->properties[$childField['id']]->value = array(1 => '');
								$property->type->complex->details->properties[$childField['id']]->type->property_info['value'] = array(1 => '');
							}
						}
					}
					// The import of files at import of listings
					if (in_array($property->getType(), array('file', 'logo', 'picture', 'video')) && $property->value !== '') {
						$field_info = SJB_ListingFieldDBManager::getListingFieldInfoByID($property->id);
						if (SJB_UploadFileManager::fileImport($listing_info, $field_info)) {
							$import_file_url = true;
						}
					}
				}

				if ($non_existed_values_flag == 'add') {
					$this->UpdateListValues($listing);
				}
				$fieldErrors = array();
				$add_listing_form = new SJB_Form($listing);
				$add_listing_form->isDataValid($fieldErrors);
				SJB_ListingManager::saveListing($listing);
				SJB_ListingManager::activateListingBySID($listing->getSID());
				$this->FillGallery($listing, $listing_info);
			}

			if ($import_file_url) {
				SJB_Filesystem::delete(SJB_System::getSystemSettings("IMPORT_FILES_DIRECTORY"));
			}

			$template_processor->assign('imported_listings_count', $count);
			$template_processor->display('import_listings_result.tpl');
		}
	}

	private function FillGallery($listing, $listing_info)
	{
		$gallery = new SJB_ListingGallery();
		$gallery->setListingSID($listing->getSID());

		if (isset($listing_info['pictures'])) {
			foreach ($listing_info['pictures'] as $picture)
				$gallery->uploadImage($picture, '');
		}
	}

	private function CreateListing($listing_info, $listing_type_id)
	{
		$listing_type_sid = SJB_ListingTypeManager::getListingTypeSIDByID($listing_type_id);
		$listing = new SJB_Listing($listing_info, $listing_type_sid);

		if (!empty($listing_info['username'])) {
			$user_info = SJB_UserManager::getUserInfoByUserName($listing_info['username']);
			$listing->setUserSID($user_info['sid']);
		}
		return $listing;
	}

	private function UpdateListValues($listing)
	{
		$list_properties = array();

		$details = $listing->getDetails();
		$properties = $details->getProperties();

		foreach ($properties as $property) {
			if ($property->getType() == 'list') {
				$list_properties[$property->getID()] = $property;
			}
		}

		$listingFieldListItemManager = new SJB_ListingFieldListItemManager();

		foreach ($list_properties as $property) {
			$property_sid = $property->getSID();
			$property_value = $property->getValue();

			if (!empty($property_value)) {
				$list_item = $listingFieldListItemManager->getListItemByValue($property->getSID(), $property->getValue());

				if (empty($list_item)) {
					$list_item = new SJB_ListItem();
					$list_item->setFieldSID($property_sid);
					$list_item->setValue($property_value);

					$listingFieldListItemManager->saveListItem($list_item);
				}
			}
		}
	}
}